﻿using AnesSystem.ViewModels;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace AnesSystem
{
    public class BaseWindow : Window
    {
        #region Variables

        private Button maxBtn;
        private Button minBtn;
        private Button closeBtn;
        private UserControl tbTitle;

        private Key downKey;
        ScaleTransform _viewScaleTransform;

        #endregion

        #region Constructor

        public BaseWindow() : base()
        {
            InitializeStyle();
            base.WindowStyle = WindowStyle.None;
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
            this.Loaded += delegate
            {
                InitializeEvent();
            };
        }

        #endregion

        #region Properties

        public new WindowStyle WindowStyle
        {
            set
            {
                if (value == WindowStyle.ToolWindow)
                {
                    minBtn.Visibility = Visibility.Collapsed;
                    maxBtn.Visibility = Visibility.Collapsed;
                }
                else if (value == WindowStyle.None)
                {
                    minBtn.Visibility = Visibility.Collapsed;
                    maxBtn.Visibility = Visibility.Collapsed;
                    closeBtn.Visibility = Visibility.Collapsed;
                }
            }
        }

        public new object Title
        {
            set
            {
                tbTitle.Content = value;
            }
            get
            {
                return tbTitle.Content;
            }
        }

        public double CusFontSize
        {
            set
            {
                tbTitle.FontSize = value;
            }
        }

        public FrameworkElement ZoomControl { get; set; }

        #endregion

        #region Event

        public event EventHandler PageDisplayed;
        public event EventHandler Collapsed;

        #endregion

        #region Private Methods

        private void InitializeStyle()
        {
            this.Style = (Style)App.Current.Resources["BaseWindowStyle"];
        }

        private void InitializeEvent()
        {
            ControlTemplate baseWindowTemplate = (ControlTemplate)App.Current.Resources["BaseWindowControlTemplate"];

            minBtn = (Button)baseWindowTemplate.FindName("btnMin", this);
            minBtn.Click += delegate
            {
                this.WindowState = WindowState.Minimized;
            };

            maxBtn = (Button)baseWindowTemplate.FindName("btnMax", this);
            maxBtn.Click += delegate
            {
                this.WindowState = (this.WindowState == WindowState.Normal ? WindowState.Maximized : WindowState.Normal);
            };

            closeBtn = (Button)baseWindowTemplate.FindName("btnClose", this);
            closeBtn.Content = "×";
            closeBtn.FontSize = 24;
            closeBtn.FontWeight = FontWeights.Bold;
            closeBtn.Foreground = new SolidColorBrush(Colors.White);
            closeBtn.BorderThickness = new Thickness(0);
            closeBtn.Background = new SolidColorBrush(Colors.Transparent);
            closeBtn.Click += delegate
            {
                CloseWin(false);
            };
            tbTitle = (UserControl)baseWindowTemplate.FindName("tbTitle", this);


            Border borderTitle = (Border)baseWindowTemplate.FindName("borderTitle", this);
            borderTitle.MouseMove += delegate (object sender, MouseEventArgs e)
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    this.DragMove();
                }
            };
            borderTitle.MouseLeftButtonDown += delegate (object sender, MouseButtonEventArgs e)
            {
                if (e.ClickCount >= 2)
                {
                    maxBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
            };
            this.PreviewKeyDown += BaseWindow_PreviewKeyDown;
            this.PreviewKeyUp += BaseWindow_PreviewKeyUp;
            this.PreviewMouseWheel += BaseWindow_PreviewMouseWheel;
        }

        #endregion

        #region Public/Protected Methods

        /// <summary>
        /// 关闭窗体，默认为隐藏
        /// </summary>
        /// <param name="isRealClose"></param>
        public void CloseWin(bool isRealClose = false)
        {
            MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Collapsed;
            if (isRealClose)
            {
                this.Close();
            }
            else
            {
                this.Visibility = Visibility.Collapsed;
                Collapsed?.Invoke(this, null);
            }
        }

        public new void ShowDialog()
        {
            MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Visible;
            this.Topmost = true;
            this.Show();
            Focus();
            PageDisplayed?.Invoke(this.Content, null);
        }

        #endregion

        #region EventHandlers



        #region 窗口事件函数

        /// <summary>
        /// 窗口移动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void TitleBar_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }

        /// <summary>
        /// 窗口最大化与还原
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void btn_max_Click(object sender, RoutedEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
            {
                this.WindowState = WindowState.Normal; //设置窗口还原
            }
            else
            {
                this.WindowState = WindowState.Maximized; //设置窗口最大化
            }
        }

        /// <summary>
        /// 窗口最小化事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_min_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized; //设置窗口最小化
        }

        /// <summary>
        /// 关闭窗口事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void btn_close_Click(object sender, RoutedEventArgs e)
        {
            CloseWin(false);
        }

        int i = 0;
        /// <summary>
        /// 双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void dpTitle_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //如果是右键点击，直接返回
            if (e.RightButton == MouseButtonState.Pressed)
                return;

            i += 1;
            System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 0, 0, 300);
            timer.Tick += (s, e1) => { timer.IsEnabled = false; i = 0; };
            timer.IsEnabled = true;

            //如果不是双击，直接返回
            if (i % 2 != 0)
                return;

            timer.IsEnabled = false;
            i = 0;
            this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
        }

        private void BaseWindow_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (PrintTemplate.PrintVisul == null) return;
            if (PrintTemplate.PrintVisul != null && downKey == Key.LeftCtrl)
            {
                if (e.Delta < 0)
                {
                    PrintTemplate.PrintVisul.ScaleView(false);
                }
                else
                {
                    PrintTemplate.PrintVisul.ScaleView(true);
                }
            }
        }

        private void BaseWindow_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            downKey = Key.None;
        }

        private void BaseWindow_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (DataManager.Instance.CurrentControl == null) return;
                if (e.Key == Key.LeftCtrl)
                {
                    downKey = e.Key;
                }
                if (e.Key == Key.Enter)
                {
                    if (!HotKeyManger.Instance.IsDropDownOpen)
                    {
                        TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);

                        UIElement focusElement = Keyboard.FocusedElement as UIElement;
                        if (focusElement != null)
                        {
                            focusElement.MoveFocus(request);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                Common.LogHelper.Error(this.GetType(), ex);
            }
        }

        #endregion 窗口事件函数

        #endregion
    }
}